package cn.doitedu.rtmk.demo8.model_inject;

import cn.doitedu.rtmk.demo8.RuleCalculator;
import groovy.lang.GroovyClassLoader;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GroovyCompileTest {

    @Test
    public  void test1() throws Exception {
        String groovyCode = "package cn.doitedu.rtmk.demo8.model_inject\n" +
                "\n" +
                "public class GroovyHelloWorld {\n" +
                "\n" +
                "    public static void main(String[] args) {\n" +
                "        for(int i=0;i<5;i++) {\n" +
                "            System.out.println(\"hello world\");\n" +
                "            //println(\"hello world\")\n" +
                "        }\n" +
                "    }\n" +
                "\n" +
                "\n" +
                "    public void sayHello(String name){\n" +
                "        System.out.println(\"hello \"+ name)\n" +
                "    }\n" +
                "\n" +
                "}";

        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
        // 这一句话完成了2件事： 编译、类加载
        Class aClass = groovyClassLoader.parseClass(groovyCode);

        Object obj = aClass.newInstance();
        Method sayHello = aClass.getMethod("sayHello", String.class);

        sayHello.invoke(obj,"zhangsan");

    }


    @Test
    public void test2() throws Exception {
        String code = "package cn.doitedu.rtmk.demo8.model_inject;\n" +
                "\n" +
                "import cn.doitedu.rtmk.common.EventBean;\n" +
                "import cn.doitedu.rtmk.demo8.RuleCalculator;\n" +
                "import org.apache.flink.api.common.functions.RuntimeContext;\n" +
                "import org.apache.flink.util.Collector;\n" +
                "import org.roaringbitmap.longlong.Roaring64Bitmap;\n" +
                "\n" +
                "import java.io.IOException;\n" +
                "\n" +
                "public class DemoRuleModelCalculator implements RuleCalculator {\n" +
                "    @Override\n" +
                "    public void init(RuntimeContext runtimeContext, String ruleParamJsonStr, Roaring64Bitmap preSelectUsersBitmap) throws IOException {\n" +
                "        System.out.println(\"我被初始化\");\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public void calc(EventBean eventBean, Collector<String> collector) throws IOException {\n" +
                "        System.out.println(\"我计算\");\n" +
                "    }\n" +
                "}";

        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
        Class aClass = groovyClassLoader.parseClass(code);
        RuleCalculator ruleCalculator = (RuleCalculator) aClass.newInstance();
        ruleCalculator.init(null,null,null);
        ruleCalculator.calc(null,null);

    }

}
